from django.shortcuts import render
from django import http
from django.conf import settings
from django_redis import get_redis_connection
from QQLoginTool.QQtool import OAuthQQ
import logging,json,re
from .models import OAuthQQUser
from meiduo_mall.apps.oauth.utils import generate_access_token,check_access_token
from django.contrib.auth import login
from users.models import User
logger = logging.Logger
# Create your views here.

from django.views import View

# 提供 QQ登录页面的网址
class QQFirstView(View):

    def get(self,request):

        next = request.GET.get('next')

        # 创键OAuthQQ类的对象

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # 获取对象的地址
        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': 0,  'errmsg': 'OK', 'login_url':login_url})


# 扫码登录后的一个回调地址
# 判断是否有code
  # 没有返回 加密的 openid
  # 有code 响应OK
class QQUserView(View):
    def get(self,request):

        code = request.GET.get('code')

        # if not code:
        #     return http.JsonResponse({'code': 400, 'errmsg': '缺少code参数'})

        # 有 code 就要进行用code 得到 access_token 和 openid

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        try:
            # 用code 申请 access_token
            access_token = oauth.get_access_token(code)

            # 再得到openid
            openid = oauth.get_open_id(access_token)

        except Exception as e :
            print(e)
            # 上面取值出错 返回错误信息
            return http.JsonResponse({'code': 400,'errmsg': 'oauth2.0认证失败, 即获取qq信息失败'})


        # 如果获取openid成功 代表用户身份没问题

        # 根据openid 获取user对象 如果获取不到对象 就说明用户没绑定 返回加密后的openid返回
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print (e)
            # 没有找到 对 openid 加密 返回
            token = generate_access_token(openid)

            return  http.JsonResponse({'code': 400,'errmsg': '未绑定','access_token': token})

        else:
            # 根据openid 找到对象 说明已经绑定美多账号
            # 做状态保持 设置cookie 返回
            login(request,qq_user.user)
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username',qq_user.user.username,max_age=3600 * 24 * 14)
            return response



    def post(self,request):

        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')

        # 校验
        if not all([mobile, password, sms_code, access_token]):
            return http.JsonResponse({'code': 400, 'errmsg': '参数缺失！'})

            # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '请输入正确的手机号码'})

            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '请输入8-20位的密码'})

        # 验证成功 连接数据库
        conn = get_redis_connection('verify_code')

        # 从数据库提取验证码信息
        sms_code_from_redis = conn.get('sms_%s' % sms_code)

        if not sms_code_from_redis:
            return http.JsonResponse({'code': 400, 'errmsg': '手机验证码过期！'})

        if sms_code != sms_code_from_redis.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '验证码有误'})

        # 获取openid 进行解密
        openid = check_access_token(access_token)

        # r如果没openid token无效
        if openid is None:
            return http.JsonResponse({'code': 400, 'errmsg': 'token无效！'})

        # 根绝用户输入的手机号 判断用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist as e:
            # 不存在新建绑定
           user = User.objects.create_user(  username=mobile,mobile=mobile,password=password)

        try:
            OAuthQQUser.objects.create(user=user,openid=openid)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '用户绑定失败！'})

        else: #存在直接绑定
            # 校验密码
            if not user.check_password(password):
                return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误！'})
            try:
                 OAuthQQUser.objects.create(user_id=user.id, openid=openid)
            except Exception as e:
                return http.JsonResponse({'code': 400, 'errmsg': '用户绑定失败！'})

        # 构建响应
        login(request,user)
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)
        return response











